<?php
class Code{
	private $img;
	private $width;
	private $height;
	private $bgColor;
	private $len;
	private	$size;
	public function __construct($width=NULL,$height=NULL,$bgColor=NULL){
		$this->width = is_null($width) ? 150 : $width;
		$this->height = is_null($height) ? 35 : $height;
		$this->bgColor = is_null($bgColor) ? '#cccccc' : $bgColor;
		$this->len = 4;
		$this->size = 15;
	}
	public function make(){
		//发头部
		header('Content-type:image/png');
		//创建画布,填充
		$this->createBg();
		//写字
		$this->write();
		//干扰
		$this->makeTrouble();
		//输出显示
		imagepng($this->img);
		//销毁
		imagedestroy($this->img);
	}
	private function createBg(){
		$img = imagecreatetruecolor($this->width, $this->height);
		//把16进制转化为10进制
		$color = hexdec($this->bgColor);
		imagefill($img, 0, 0, $color);
		$this->img = $img;
	}
	private function write(){
		$str = '' ;
		for ($i=0; $i < $this->len; $i++) {
			$x =  $this->width / $this->len * $i + 10;
			$y = ($this->height + $this->size) /2;
			$text = md5(microtime(true));
			//因为md5之后的值是32位，下标是0开始
			$text = $text[mt_rand(0, 31)];
			$str .= $text;
			$color = imagecolorallocate($this->img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
			imagettftext($this->img, 28, mt_rand(-45, 45),$x, $y, $color, './Tool/font.ttf', $text);
		}
		$_SESSION['code'] = strtolower($str);
	}
	//干扰
	//矩形边框
	private function makeTrouble(){
		$black = '#000000';
		$color = hexdec($black);
		imagerectangle($this->img, 0, 0, $this->width-1, $this->height-1, $color);
		//圆
		for ($i=0; $i <10; $i++) {
			$cx = mt_rand(0, $this->width-1);
			$cy = mt_rand(0 , $this->height-1);
			$wh = mt_rand(0, 20);
			$color = imagecolorallocate($this->img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
			imageellipse($this->img, $cx, $cy, $wh,$wh, $color);
		}
		//线
		for ($i=0; $i < 2; $i++) {
			$color = imagecolorallocate($this->img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
			imageline($this->img, mt_rand(0, $this->width),  mt_rand(0, $this->height), mt_rand(0, $this->width),  mt_rand(0, $this->height), $color);
		}
		//点
		for ($i=0; $i < 10; $i++) {
			$color = imagecolorallocate($this->img, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
			imagesetpixel($this->img, mt_rand(0,  $this->width-1), mt_rand(0,  $this->height-1),$color);
		}

	}
}

?>